//
//  WUtil.m
//
//  Created by ladaka31 ladaka on 13. 5. 31..
//  Copyright (c) 2013년 ladaka Inc. All rights reserved.


#import "WUtil.h"
#import <QuartzCore/QuartzCore.h>
#import "DateUtils.h"

#include <stdio.h>
#include <stdlib.h>
#include <ifaddrs.h>
#include <string.h>
#include <stdbool.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <arpa/inet.h>
#include <ifaddrs.h>

#if ! defined(IFT_ETHER)
#define IFT_ETHER 0x6/* Ethernet CSMACD */
#endif

@implementation WUtil

+ (NSString *)getMacAddress
{
	NSString *mac_address = @"";
	
	bool success;
	struct ifaddrs *addrs;
	const struct ifaddrs *cursor;
	const struct sockaddr_dl *dlAddr;
	const uint8_t *base;
	int i;
	
	success = getifaddrs(&addrs) == 0;
	if (success) {
		cursor = addrs;
		while (cursor != NULL) {
			if ((cursor->ifa_flags & IFF_LOOPBACK) == 0 ) {
				//printf("%s ", (char *)cursor->ifa_name);
				//printf("%s\n",inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr));
			}
            
			if ( (cursor->ifa_addr->sa_family == AF_LINK)
				&& (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type ==IFT_ETHER)
				)
            {
				dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
				//      fprintf(stderr, " sdl_nlen = %d\n", dlAddr->sdl_nlen);
				//      fprintf(stderr, " sdl_alen = %d\n", dlAddr->sdl_alen);
				base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
				//printf(" MAC address ");
				for (i = 0; i < dlAddr->sdl_alen; i++)
                {
                    //					if (i != 0) {
                    //						printf(":");
                    //                    }
                    //printf("%02x", base[i]);
                    NSString* addr_assembly = [NSString stringWithFormat:@"%02x",base[i]];
                    mac_address = [mac_address stringByAppendingFormat:@"%@", addr_assembly];
					
				}
				NSString *ifa_name = [NSString stringWithFormat:@"%s", (char *)cursor->ifa_name];
				
				if([ifa_name isEqualToString:@"en0"] == TRUE)
                {
                    freeifaddrs(addrs);
					return mac_address;
                }
				
				
				mac_address = @"";
				//printf("\n");
			}
			cursor = cursor->ifa_next;
		}
        freeifaddrs(addrs);
	}
    return mac_address;
}

+ (BOOL)createImagePicker:(id)delgate
             myController:(UIViewController*)myController
               sourceType:(UIImagePickerControllerSourceType)sourceType
             allowEditing:(BOOL)allowEditing {
    BOOL resultValue = NO;
    
    if(YES == [UIImagePickerController isSourceTypeAvailable:sourceType]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = sourceType;
        picker.allowsEditing = YES;
        picker.delegate = delgate;
        [myController presentModalViewController:picker animated:YES];
        
        resultValue = YES;
    }
    
    return resultValue;
}


+ (UIImage *)resizeWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

+ (NSMutableArray *) savedImage:(NSArray *)arr title:(NSString *)title {
    NSMutableArray *imgArr = [[NSMutableArray alloc] init];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *imgPath = [paths objectAtIndex:0];

    NSString *filePath = nil;
    NSDate *date = [NSDate date];
    DateUtils *dateUtil = [[DateUtils alloc] init];
    NSString *strDate = [dateUtil formatDateTimeWithFormatString:@"yyyyMMddHHmmss" Date:date];
    
    for (int i=0 ; i<[arr count] ; i++) {
        NSString *fileName = [NSString stringWithFormat:@"%@_%@_%02d.jpg", title, strDate, i];
        filePath = [NSString stringWithFormat:@"%@/%@", imgPath, fileName];
        
        NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation([arr objectAtIndex:i], 1)];
        [imageData writeToFile:filePath atomically:YES];
        [imgArr addObject:filePath];
        NSLog(@"FilePath:%@", filePath);
    }
    NSLog(@"imgARR:%@", imgArr);
    return imgArr;
}

+ (NSString *)getAppName {
    NSString *str = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
    return str;
}

+ (NSString *)getVersion {
    NSString *str = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    return str;
}

+ (NSString *) getSystemVersion {
    NSString *str = [[UIDevice currentDevice] systemVersion];
    return str;
}

+ (NSString *) getDeviceModel
{
    NSString *str = [[NSString alloc] initWithFormat:@"%@", [ UIDevice currentDevice].model];
	return str;
}

+ (NSString *) getDeviceFlatform
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithUTF8String:machine];
    free(machine);
    
    /* Example
     @"iPhone 1G";
     @"iPhone 3G";
     @"iPhone 3GS";
     @"iPhone 4";
     @"Verizon iPhone 4";
     @"iPod Touch 1G";
     @"iPod Touch 2G";
     @"iPod Touch 3G";
     @"iPod Touch 4G";
     @"iPad";
     @"iPad 2 (WiFi)";
     @"iPad 2 (GSM)";
     @"iPad 2 (CDMA)";
     @"Simulator";
     */
    
    return platform;
}


+ (UIImage *) screenShot:(UIView *)view {
	// Create a graphics context with the target size
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
    
    CGSize imageSize;
    CGFloat scale = [[UIScreen mainScreen] scale];
    
	if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
	{
		if (scale == 2.f) {
            imageSize = CGSizeMake(view.frame.size.width*2, view.frame.size.height*2);
			NSLog(@"Retina!");	// iPhone 4
		} else {
            imageSize = CGSizeMake(view.frame.size.width, view.frame.size.height);
            
			NSLog(@"Non-retina!");	// iPhone3GS iOS 4.x 또는 iPad 3.2
		}
		
	} else {
		NSLog(@"Under iOS 4.0");	// OS 4.0 아래 버전
	}
	NSLog(@"imageSize:%f %f", imageSize.width, imageSize.height);
    
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    else
        UIGraphicsBeginImageContext(imageSize);
    
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    // Retrieve the screenshot image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Create rectangle that represents a cropped image
    // from the middle of the existing image
	
	CGRect rect;
	if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
	{
		CGFloat scale = [[UIScreen mainScreen] scale];
		if (scale == 2.f) {
			rect = CGRectMake(0, 0,
							  imageSize.width, imageSize.height);
		} else {
			rect = CGRectMake(0, 0,
							  imageSize.width, imageSize.height);
		}
		
	} else {
		NSLog(@"Under iOS 4.0");	// OS 4.0 아래 버전
	}
    
    // Create bitmap image from original image data,
    // using rectangle to specify desired crop area
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
    UIImage *img = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    return img;
}


+ (UIImage *) screenShotScroll:(UIScrollView *)sv {
    CGSize imageSize;
    CGFloat scale = [[UIScreen mainScreen] scale];
    
	if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
	{
		if (scale == 2.f) {
            imageSize = CGSizeMake(sv.frame.size.width*2, sv.frame.size.height*2);
			NSLog(@"Retina!");	// iPhone 4
		} else {
            imageSize = CGSizeMake(sv.frame.size.width, sv.frame.size.height);
            
			NSLog(@"Non-retina!");	// iPhone3GS iOS 4.x 또는 iPad 3.2
		}
		
	} else {
		NSLog(@"Under iOS 4.0");	// OS 4.0 아래 버전
	}
	NSLog(@"imageSize:%f %f", imageSize.width, imageSize.height);
    
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    else
        UIGraphicsBeginImageContext(imageSize);
    
    [sv.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    // Retrieve the screenshot image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
  	CGRect visibleRect;
    visibleRect.origin.x = sv.contentOffset.x * scale;
    visibleRect.origin.y = sv.contentOffset.y * scale;
    visibleRect.size.width = sv.bounds.size.width * scale;
    visibleRect.size.height = sv.bounds.size.height * scale;
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], visibleRect);
    UIImage *img = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    return img;
}


+ (UIColor*)getColorValue:(NSInteger) index {
    UIColor *color = [UIColor alloc];
    
    switch (index) {
        case 0:
            color = [color initWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
            break;
        case 1:
            color = [color initWithRed:255.0f/255.0f green:210.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
            break;
        case 2:
            color = [color initWithRed:239.0f/255.0f green:84.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
            break;
        case 3:
            color = [color initWithRed:255.0f/255.0f green:34.0f/255.0f blue:16.0f/255.0f alpha:1.0f];
            break;
        case 4:
            color = [color initWithRed:52.0f/255.0f green:172.0f/255.0f blue:177.0f/255.0f alpha:1.0f];
            break;
        case 5:
            color = [color initWithRed:34.0f/255.0f green:115.0f/255.0f blue:190.0f/255.0f alpha:1.0f];
            break;
        case 6:
            color = [color initWithRed:113.0f/255.0f green:173.0f/255.0f blue:18.0f/255.0f alpha:1.0f];
            break;
        case 7:
            color = [color initWithRed:208.0f/255.0f green:35.0f/255.0f blue:100.0f/255.0f alpha:1.0f];
            break;
        case 8:
            color = [color initWithRed:224.0f/255.0f green:93.0f/255.0f blue:119.0f/255.0f alpha:1.0f];
            break;
        case 9:
            color = [color initWithRed:105.0f/255.0f green:72.0f/255.0f blue:190.0f/255.0f alpha:1.0f];
            break;
        case 10:
            color = [color initWithRed:233.0f/255.0f green:227.0f/255.0f blue:200.0f/255.0f alpha:1.0f];
            break;
        case 11:
            color = [color initWithRed:124.0f/255.0f green:133.0f/255.0f blue:133.0f/255.0f alpha:1.0f];
            break;
        case 12:
            color = [color initWithRed:51.0f/255.0f green:51.0f/255.0f blue:51.0f/255.0f alpha:1.0f];
            break;
        case 13:
            color = [color initWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
            break;
        default:
            break;
    }
    return color;
}



+ (BOOL) connectedToInternet:(NSString*)url
{
    NSError *error;
    NSString* text = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSASCIIStringEncoding error:&error];
    
    return ( text != NULL ) ? YES : NO;
}




@end
